<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>应急响应终端</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .header h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 10px;
        }

        .status-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .status-item {
            text-align: center;
        }

        .status-label {
            font-size: 12px;
            color: #6c757d;
            margin-bottom: 5px;
        }

        .status-value {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }

        .status-value.text-success {
            color: #28a745;
        }

        .status-value.text-warning {
            color: #ffc107;
        }

        .status-value.text-info {
            color: #17a2b8;
        }

        .status-value.text-primary {
            color: #007bff;
        }

        .status-value.text-danger {
            color: #dc3545;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .panel {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .panel h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }

        .event-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .event-title {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .event-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            font-size: 14px;
        }

        .detail-item {
            display: flex;
            justify-content: space-between;
        }

        .detail-label {
            color: #6c757d;
        }

        .detail-value {
            font-weight: bold;
            color: #2c3e50;
        }

        .action-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
        }

        .btn-success {
            background: linear-gradient(45deg, #27ae60, #229954);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(45deg, #f39c12, #e67e22);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(45deg, #e74c3c, #c0392b);
            color: white;
        }

        .btn-info {
            background: linear-gradient(45deg, #17a2b8, #138496);
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .emergency-alert {
            background: linear-gradient(45deg, #e74c3c, #c0392b);
            color: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }

        .location-info {
            background: #e8f5e8;
            border: 1px solid #27ae60;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .safety-status {
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-weight: bold;
            text-align: center;
        }

        .safety-safe { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .safety-caution { background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
        .safety-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .safety-sos { background: #e74c3c; color: white; border: 1px solid #c0392b; }

        .support-request {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .device-status {
            display: flex;
            justify-content: space-around;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .device-item {
            text-align: center;
        }

        .timeline {
            max-height: 300px;
            overflow-y: auto;
        }

        .timeline-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-left: 3px solid #3498db;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 0 8px 8px 0;
        }

        .timeline-time {
            font-size: 12px;
            color: #6c757d;
            margin-right: 10px;
            min-width: 80px;
        }

        .timeline-content {
            flex: 1;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
            
            .action-buttons {
                grid-template-columns: 1fr;
            }
            
            .event-details {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚨 应急响应终端</h1>
            <div id="loginStatus" style="background: #fff3cd; border: 1px solid #ffeaa7; color: #856404; padding: 15px; border-radius: 8px; margin-top: 15px; text-align: center;">
                <div style="margin-bottom: 10px;">
                    <strong>🔐 登录状态检查中...</strong>
                </div>
                <div id="loginActions" style="display: none;">
                    <p style="margin-bottom: 15px;">您尚未登录或登录已过期</p>
                    <button class="btn btn-primary" onclick="goToLogin()" style="margin-right: 10px;">🔑 立即登录</button>
                    <button class="btn btn-info" onclick="checkLoginStatus()">🔄 重新检查</button>
                </div>
            </div>
            <div class="status-bar">
                <div class="status-item">
                    <div class="status-label">人员状态</div>
                    <div class="status-value" id="currentStatus">在线</div>
                </div>
                <div class="status-item">
                    <div class="status-label">在线时间</div>
                    <div class="status-value" id="onlineTime">00:00:00</div>
                    <button class="btn btn-sm btn-outline-secondary" onclick="resetOnlineTime()" style="margin-top: 5px; font-size: 10px;">重置</button>
                </div>
                <div class="status-item">
                    <div class="status-label">今日任务</div>
                    <div class="status-value" id="todayTasks">0</div>
                </div>
                <div class="status-item">
                    <div class="status-label">完成率</div>
                    <div class="status-value" id="completionRate">0%</div>
                </div>
            </div>
        </div>

        <div id="emergencyAlert" class="emergency-alert" style="display: none;">
            <h3>🚨 紧急警报</h3>
            <p id="emergencyMessage">检测到紧急情况，请立即处理！</p>
        </div>

        <div class="main-content">
            <div class="panel" id="currentEventPanel">
                <h2>📋 当前任务</h2>
                <div id="currentEventDetails"></div>
                <div id="eventMap" style="width:100%;height:320px;border-radius:10px;margin-top:16px;"></div>
                <div id="actionButtons" class="action-buttons" style="display:none;"></div>
            </div>

            <div class="panel">
                <h2>📍 位置与状态</h2>
                <div class="location-info">
                    <div class="detail-item">
                        <span class="detail-label">当前位置：</span>
                        <span class="detail-value" id="currentLocation">获取中...</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">最后更新：</span>
                        <span class="detail-value" id="lastLocationUpdate">-</span>
                    </div>
                </div>
                
                <div class="action-buttons" style="margin-bottom: 15px;">
                    <button class="btn btn-primary" onclick="getCurrentLocation()">
                        <i class="bi bi-geo-alt"></i> 获取当前位置
                    </button>
                    <button class="btn btn-outline-primary" onclick="startLocationTracking()">
                        <i class="bi bi-play-circle"></i> 开始追踪
                    </button>
                    <button class="btn btn-outline-secondary" onclick="stopLocationTracking()">
                        <i class="bi bi-stop-circle"></i> 停止追踪
                    </button>
                </div>

                <div id="safetyStatus" class="safety-status safety-safe">
                    安全状态：安全
                </div>

                <div class="action-buttons">
                    <button class="btn btn-success" onclick="updateSafetyStatus('SAFE')">安全</button>
                    <button class="btn btn-warning" onclick="updateSafetyStatus('CAUTION')">注意</button>
                    <button class="btn btn-danger" onclick="updateSafetyStatus('DANGER')">危险</button>
                    <button class="btn btn-danger" onclick="sendSOS()">SOS</button>
                </div>

                <div id="supportRequest" class="support-request" style="display: none;">
                    <h4>🆘 支援请求</h4>
                    <p id="supportInfo">已请求支援</p>
                    <button class="btn btn-warning" onclick="cancelSupport()">取消支援</button>
                </div>

                <div class="action-buttons">
                    <button class="btn btn-info" onclick="requestSupport('MEDICAL', '需要医疗支援')">医疗支援</button>
                    <button class="btn btn-info" onclick="requestSupport('POLICE', '需要警力支援')">警力支援</button>
                    <button class="btn btn-info" onclick="requestSupport('FIRE', '需要消防支援')">消防支援</button>
                </div>
            </div>
        </div>

        <div class="panel" id="timelinePanel" style="display: none;">
            <h2>📊 任务时间线</h2>
            <div id="timeline" class="timeline">
                <div class="loading">正在加载时间线...</div>
            </div>
        </div>

        <div class="panel">
            <h2>📚 历史任务</h2>
            <div class="action-buttons" style="margin-bottom: 15px;">
                <button class="btn btn-info" onclick="loadTodayCompletedEvents()">今日完成</button>
                <button class="btn btn-info" onclick="loadEventHistory()">历史记录</button>
            </div>
            <div id="historyEvents" class="timeline">
                <div class="loading">点击上方按钮加载历史任务</div>
            </div>
        </div>
    </div>

    <!-- 高德地图API（如有本地包可替换，否则用CDN） -->
    <script>
    window._AMapSecurityConfig = { securityJsCode: 'bd7cfe5378f27ad4720f0279a1b184a7' };
    </script>
    <script>
        // AMap加载状态管理
        window.amapLoadStatus = {
            loaded: false,
            error: false,
            retryCount: 0,
            maxRetries: 3
        };
        
        function loadAMapScript() {
            return new Promise((resolve, reject) => {
                if (window.amapLoadStatus.loaded) {
                    resolve();
                    return;
                }
                
                if (window.amapLoadStatus.error && window.amapLoadStatus.retryCount >= window.amapLoadStatus.maxRetries) {
                    reject(new Error('AMap加载失败，已达到最大重试次数'));
                    return;
                }
                
                const script = document.createElement('script');
                script.src = 'https://webapi.amap.com/maps?v=2.0&key=9c44b0918d292a11356bd716509f09c3';
                script.onload = () => {
                    window.amapLoadStatus.loaded = true;
                    console.log('AMap加载成功');
                    resolve();
                };
                script.onerror = () => {
                    window.amapLoadStatus.error = true;
                    window.amapLoadStatus.retryCount++;
                    console.error(`AMap加载失败，重试次数: ${window.amapLoadStatus.retryCount}`);
                    reject(new Error('AMap脚本加载失败'));
                };
                document.head.appendChild(script);
            });
        }
        
        // 页面加载时尝试加载AMap
        loadAMapScript().catch(error => {
            console.error('AMap初始加载失败:', error);
        });
    </script>
    <script th:src="@{/js/auth.js}"></script>

    <script>
        let currentEvent = null;
        let onlineStartTime = getOnlineStartTime();
        let isLoggedIn = false;
        let locationTrackingInterval = null; // 位置追踪定时器
        let isLocationTracking = false; // 位置追踪状态
        let amapLoaded = false; // AMap加载状态

        // 获取在线开始时间，如果不存在则创建新的
        function getOnlineStartTime() {
            const savedStartTime = localStorage.getItem('terminalOnlineStartTime');
            if (savedStartTime) {
                const startTime = parseInt(savedStartTime);
                const now = Date.now();
                const elapsed = now - startTime;
                const maxOnlineTime = 24 * 60 * 60 * 1000; // 24小时
                
                // 如果在线时间超过24小时，自动重置
                if (elapsed > maxOnlineTime) {
                    const newStartTime = now;
                    localStorage.setItem('terminalOnlineStartTime', newStartTime.toString());
                    return newStartTime;
                }
                
                return startTime;
            } else {
                const newStartTime = Date.now();
                localStorage.setItem('terminalOnlineStartTime', newStartTime.toString());
                return newStartTime;
            }
        }

        // 重置在线时间（可选功能）
        function resetOnlineTime() {
            const newStartTime = Date.now();
            localStorage.setItem('terminalOnlineStartTime', newStartTime.toString());
            onlineStartTime = newStartTime;
            updateOnlineTime();
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', async function() {
            // JWT认证检查
            if (!window.AuthManager || !AuthManager.isAuthenticated()) {
                showAccessDenied();
                return;
            }
            // 检查token有效性
            try {
                await AuthManager.verifyToken();
            } catch (e) {
                showAccessDenied();
                return;
            }
            
            checkLoginStatus();
            loadCurrentEvent();
            updateOnlineTime();
            updatePersonnelStatus();
            
            // 初始化安全状态和支援请求显示
            updateSafetyStatusDisplay('SAFE');
            updateSupportRequestDisplay(false, null);
            
            // 加载上次保存的位置信息
            loadLastKnownLocation();
            
            setInterval(updateOnlineTime, 1000);
            setInterval(updatePersonnelStatus, 5000); // 每5秒更新一次人员状态
            loadTodayCompletedCount();
            
            // 初始化位置追踪按钮状态
            updateLocationTrackingButtons();
        });

        // 显示访问被拒绝
        function showAccessDenied() {
            document.body.innerHTML = '<div class="access-denied" style="text-align:center;padding:50px 20px;color:#6c757d;"><i class="bi bi-shield-exclamation" style="font-size:4rem;margin-bottom:20px;"></i><h3>访问被拒绝</h3><p>请先登录系统。</p><a href="/ercms/login" class="btn btn-primary">去登录</a></div>';
        }

        // 检查登录状态
        async function checkLoginStatus() {
            const loginStatusDiv = document.getElementById('loginStatus');
            const loginActionsDiv = document.getElementById('loginActions');
            
            try {
                // 显示检查中状态
                loginStatusDiv.innerHTML = `
                    <div style="margin-bottom: 10px;">
                        <strong>🔐 正在检查登录状态...</strong>
                    </div>
                    <div style="font-size: 12px; color: #666;">请稍候...</div>
                `;
                loginActionsDiv.style.display = 'none';
                
                const response = await fetch('/ercms/auth/status', {
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    const result = await response.json();
                    if (result.authenticated) {
                        isLoggedIn = true;
                        // 显示已登录状态
                        loginStatusDiv.innerHTML = `
                            <div style="background: #d4edda; border: 1px solid #c3e6cb; color: #155724; padding: 10px; border-radius: 5px;">
                                <strong>✅ 已登录</strong> - 用户: ${result.username || '未知'} (${result.role || '未知角色'})
                            </div>
                        `;
                        loadCurrentEvent();
                        // 更新人员状态
                        updatePersonnelStatus();
                    } else {
                        showLoginRequired();
                    }
                } else {
                    showLoginRequired();
                }
            } catch (error) {
                console.error('检查登录状态失败', error);
                showLoginRequired();
            }
        }

        // 显示需要登录的提示
        function showLoginRequired() {
            const loginStatusDiv = document.getElementById('loginStatus');
            const loginActionsDiv = document.getElementById('loginActions');
            
            loginStatusDiv.innerHTML = `
                <div style="margin-bottom: 10px;">
                    <strong>🔐 登录状态检查中...</strong>
                </div>
                <div id="loginActions" style="display: block;">
                    <p style="margin-bottom: 15px; color: #721c24;">您尚未登录或登录已过期</p>
                    <button class="btn btn-primary" onclick="goToLogin()" style="margin-right: 10px;">🔑 立即登录</button>
                    <button class="btn btn-info" onclick="checkLoginStatus()">🔄 重新检查</button>
                </div>
            `;
            
            // 清空当前任务区域
            document.getElementById('currentEventDetails').innerHTML = `
                <div style="text-align: center; padding: 40px; color: #6c757d;">
                    <h3>🔒 需要登录</h3>
                    <p>请先登录系统才能使用终端功能</p>
                    <p style="font-size: 14px; margin-top: 20px;">如果您已经登录，请点击上方重新检查按钮</p>
                </div>
            `;
            document.getElementById('eventMap').innerHTML = '';
            document.getElementById('actionButtons').style.display = 'none';
            // 需要登录时隐藏时间线面板
            document.getElementById('timelinePanel').style.display = 'none';
            // 更新人员状态为离线
            updatePersonnelStatus();
            // 重置安全状态和支援请求显示
            updateSafetyStatusDisplay('SAFE');
            updateSupportRequestDisplay(false, null);
        }

        // 跳转到登录页面
        function goToLogin() {
            window.location.href = '/ercms/login';
        }

        // 显示错误信息
        function showError(message) {
            const errorHtml = `
                <div style="background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 15px; border-radius: 5px; margin-bottom: 15px;">
                    <strong>错误:</strong> ${message}
                </div>
            `;
            document.getElementById('currentEventDetails').insertAdjacentHTML('afterbegin', errorHtml);
        }

        // 显示成功信息
        function showSuccess(message) {
            const successHtml = `
                <div style="background: #d4edda; border: 1px solid #c3e6cb; color: #155724; padding: 15px; border-radius: 5px; margin-bottom: 15px;">
                    <strong>成功:</strong> ${message}
                </div>
            `;
            document.getElementById('currentEventDetails').insertAdjacentHTML('afterbegin', successHtml);
        }

        // 更新在线时间
        function updateOnlineTime() {
            const elapsed = Date.now() - onlineStartTime;
            const hours = Math.floor(elapsed / 3600000);
            const minutes = Math.floor((elapsed % 3600000) / 60000);
            const seconds = Math.floor((elapsed % 60000) / 1000);
            document.getElementById('onlineTime').textContent = 
                `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }

        // 加载当前任务
        async function loadCurrentEvent() {
            try {
                const response = await fetch('/ercms/api/events/my-current-event', {
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    currentEvent = await response.json();
                    displayCurrentEvent(currentEvent);
                    loadTimeline(currentEvent.id);
                    // 显示时间线面板
                    document.getElementById('timelinePanel').style.display = 'block';
                    // 更新完成率
                    loadTodayCompletedCount();
                } else if (response.status === 404) {
                    currentEvent = null;
                    document.getElementById('currentEventDetails').innerHTML = '<div class="no-event">暂无当前任务</div>';
                    document.getElementById('eventMap').innerHTML = '';
                    document.getElementById('actionButtons').style.display = 'none';
                    // 没有当前任务时隐藏时间线面板
                    document.getElementById('timelinePanel').style.display = 'none';
                    // 更新完成率
                    loadTodayCompletedCount();
                    // 重置安全状态和支援请求显示
                    updateSafetyStatusDisplay('SAFE');
                    updateSupportRequestDisplay(false, null);
                } else {
                    const error = await response.text();
                    showError('加载当前任务失败: ' + error);
                    // 重置安全状态和支援请求显示
                    updateSafetyStatusDisplay('SAFE');
                    updateSupportRequestDisplay(false, null);
                }
            } catch (error) {
                console.error('加载当前任务失败:', error);
                showError('加载当前任务失败: ' + error.message);
                // 重置安全状态和支援请求显示
                updateSafetyStatusDisplay('SAFE');
                updateSupportRequestDisplay(false, null);
            }
        }

        // 显示当前任务
        function displayCurrentEvent(event) {
            const actionButtons = document.getElementById('actionButtons');
            if (!event) {
                document.getElementById('currentEventDetails').innerHTML = '<div class="no-event">暂无任务</div>';
                document.getElementById('eventMap').innerHTML = '';
                if (actionButtons) actionButtons.style.display = 'none';
                // 没有任务时隐藏时间线面板
                document.getElementById('timelinePanel').style.display = 'none';
                // 更新人员状态
                updatePersonnelStatus();
                // 重置安全状态和支援请求显示
                updateSafetyStatusDisplay('SAFE');
                updateSupportRequestDisplay(false, null);
                return;
            }
            // 优先级、响应状态、严重程度中文映射
            const priorityText = getPriorityText(event.priority);
            const severityText = getSeverityText(event.severity);
            const statusText = getStatusText(event.responderStatus);
            // 事件位置字段
            let locationText = event.location || '暂无定位信息';
            
            document.getElementById('currentEventDetails').innerHTML = `
                <div class="event-info">
                    <div class="event-title">${event.title || ''}</div>
                    <div class="event-details">
                        <div class="detail-item"><span class="detail-label">事件类型：</span><span class="detail-value">${event.eventType ? event.eventType.name : ''}</span></div>
                        <div class="detail-item"><span class="detail-label">优先级：</span><span class="detail-value">${priorityText}</span></div>
                        <div class="detail-item"><span class="detail-label">严重程度：</span><span class="detail-value">${severityText}</span></div>
                        <div class="detail-item"><span class="detail-label">响应状态：</span><span class="detail-value">${statusText}</span></div>
                        <div class="detail-item"><span class="detail-label">事件位置：</span><span class="detail-value" id="eventLocation">${locationText}</span></div>
                        <div class="detail-item"><span class="detail-label">描述：</span><span class="detail-value">${event.description || ''}</span></div>
                    </div>
                </div>
            `;
            // 异步渲染地图
            renderEventMap(event).catch(error => {
                console.error('渲染地图失败:', error);
            });
            // 有任务时显示时间线面板
            document.getElementById('timelinePanel').style.display = 'block';
            if (actionButtons) {
                let buttons = '';
                const status = event.responderStatus;
                
                // 根据事件状态显示不同的按钮
                if (status === 'PENDING') {
                    buttons = `
                        <button class="btn btn-success btn-sm" onclick="acceptEvent(${event.id})">
                            <i class="bi bi-check-circle"></i> 接受任务
                        </button>
                    `;
                } else if (status === 'ASSIGNED') {
                    buttons = `
                        <button class="btn btn-success btn-sm" onclick="acceptEvent(${event.id})">
                            <i class="bi bi-check-circle"></i> 接受任务
                        </button>
                    `;
                } else if (status === 'ACCEPTED') {
                    buttons = `
                        <button class="btn btn-primary btn-sm" onclick="startEnRoute(${event.id})">
                            <i class="bi bi-arrow-right-circle"></i> 开始前往
                        </button>
                    `;
                } else if (status === 'EN_ROUTE') {
                    buttons = `
                        <button class="btn btn-info btn-sm" onclick="arriveAtScene(${event.id})">
                            <i class="bi bi-geo-alt"></i> 到达现场
                        </button>
                    `;
                } else if (status === 'ARRIVED') {
                    buttons = `
                        <button class="btn btn-warning btn-sm" onclick="startProcessing(${event.id})">
                            <i class="bi bi-tools"></i> 开始处理
                        </button>
                    `;
                } else if (status === 'IN_PROGRESS') {
                    buttons = `
                        <button class="btn btn-success btn-sm" onclick="completeTask(${event.id})">
                            <i class="bi bi-check-circle"></i> 完成任务
                        </button>
                    `;
                } else if (status === 'COMPLETED') {
                    buttons = `
                        <span class="badge bg-success">已完成</span>
                        <a href="/ercms/task-report?eventId=${event.id}" class="btn btn-outline-primary btn-sm ms-2">
                            <i class="bi bi-file-text"></i> 查看报告
                        </a>
                    `;
                } else if (status === 'RETURNING') {
                    buttons = `
                        <span class="badge bg-secondary">返回中</span>
                    `;
                } else if (status === 'CLOSED') {
                    buttons = `
                        <span class="badge bg-dark">已关闭</span>
                    `;
                } else {
                    buttons = `
                        <span class="badge bg-secondary">${statusText}</span>
                    `;
                }
                
                actionButtons.innerHTML = buttons;
                actionButtons.style.display = buttons ? 'grid' : 'none';
            }
            
            // 更新人员状态
            updatePersonnelStatus();
            
            // 更新安全状态显示
            if (event.safetyStatus) {
                updateSafetyStatusDisplay(event.safetyStatus);
            }
            
            // 更新支援请求显示
            if (event.supportRequested !== undefined) {
                updateSupportRequestDisplay(event.supportRequested, event.supportType);
            }
        }

        function openTaskReport() {
            if (!currentEvent) return;
            window.location.href = '/ercms/task-report?eventId=' + currentEvent.id;
        }

        function getPriorityText(priority) {
            const map = { 'HIGH': '高', 'MEDIUM': '中', 'LOW': '低' };
            return map[priority] || priority || '';
        }
        function getSeverityText(severity) {
            const map = { 'MINOR': '一般', 'MODERATE': '较重', 'SEVERE': '严重', 'CRITICAL': '危险' };
            return map[severity] || severity || '';
        }
        function getStatusText(status) {
            const map = { 
                'ASSIGNED': '已指派', 
                'ACCEPTED': '已接受', 
                'EN_ROUTE': '正在前往', 
                'ARRIVED': '到达现场', 
                'IN_PROGRESS': '开始处理', 
                'COMPLETED': '完成任务', 
                'RETURNING': '正在返程',
                'RESOLVED': '已解决', 
                'CLOSED': '已关闭' 
            };
            return map[status] || status || '';
        }

        // 渲染事件地图
        async function renderEventMap(event) {
            if (!event) return;
            
            // 事件位置 - 使用Event.location字段
            let eventLat = null;
            let eventLng = null;
            if (event.location && event.location.includes(',')) {
                const parts = event.location.split(',');
                if (parts.length === 2) {
                    eventLng = Number(parts[0].trim());
                    eventLat = Number(parts[1].trim());
                }
            }
            
            if (isNaN(eventLat) || isNaN(eventLng)) {
                document.getElementById('eventMap').innerHTML = '<div class="text-muted text-center pt-5">暂无事件定位信息</div>';
                return;
            }
            
            // 等待AMap加载完成
            const amapReady = await checkAMapLoaded();
            if (!amapReady) {
                document.getElementById('eventMap').innerHTML = '<div class="text-muted text-center pt-5">地图加载失败，请刷新页面重试</div>';
                return;
            }
            
            try {
                const map = new AMap.Map('eventMap', {
                    zoom: 16,
                    center: [eventLng, eventLat],
                    viewMode: '3D'
                });
                
                // 事件位置标记（红色）
                const eventMarker = new AMap.Marker({
                    position: new AMap.LngLat(eventLng, eventLat),
                    map: map,
                    title: '事件位置',
                    icon: new AMap.Icon({
                        size: new AMap.Size(32, 32),
                        image: ''
                    })
                });
                
                // 异步获取最新响应者位置并显示
                loadLatestResponderLocation(event.id, map, eventLat, eventLng);
                
                // 创建信息窗体，添加错误处理
                let infoWindow = null;
                try {
                    infoWindow = new AMap.InfoWindow({ anchor: 'top-center' });
                } catch (error) {
                    console.error('创建信息窗体失败:', error);
                    infoWindow = null;
                }
                
                // 使用setTimeout确保AMap完全加载后再加载插件
                setTimeout(() => {
                    if (typeof AMap !== 'undefined' && AMap.plugin) {
                        AMap.plugin('AMap.Geocoder', function() {
                            try {
                                const geocoder = new AMap.Geocoder({ city: '全国' });
                                geocoder.getAddress([eventLng, eventLat], function(status, result) {
                                    let address = `${eventLng},${eventLat}`;
                                    if (status === 'complete' && result && result.regeocode) {
                                        address = result.regeocode.formattedAddress;
                                    }
                                    document.getElementById('eventLocation').textContent = address;
                                    
                                    // 安全地设置和打开信息窗体
                                    try {
                                        if (infoWindow) {
                                            infoWindow.setContent(`
                                                <div style="padding: 8px;">
                                                    <h6>事件位置</h6>
                                                    <p>${address}</p>
                                                </div>
                                            `);
                                            
                                            // 确保地图和标记都存在且有效
                                            if (map && eventMarker && eventMarker.getPosition) {
                                                const position = eventMarker.getPosition();
                                                if (position) {
                                                    infoWindow.open(map, position);
                                                }
                                            }
                                        }
                                    } catch (infoError) {
                                        console.error('信息窗体操作失败:', infoError);
                                    }
                                });
                            } catch (error) {
                                console.error('地理编码失败:', error);
                                // 如果地理编码失败，仍然显示坐标
                                const address = `${eventLng},${eventLat}`;
                                document.getElementById('eventLocation').textContent = address;
                                
                                // 安全地设置和打开信息窗体
                                try {
                                    if (infoWindow) {
                                        infoWindow.setContent(`
                                            <div style="padding: 8px;">
                                                <h6>事件位置</h6>
                                                <p>${address}</p>
                                            </div>
                                        `);
                                        
                                        // 确保地图和标记都存在且有效
                                        if (map && eventMarker && eventMarker.getPosition) {
                                            const position = eventMarker.getPosition();
                                            if (position) {
                                                infoWindow.open(map, position);
                                            }
                                        }
                                    }
                                } catch (infoError) {
                                    console.error('信息窗体操作失败:', infoError);
                                }
                            }
                        });
                    } else {
                        console.error('AMap.Geocoder插件加载失败');
                        // 如果插件加载失败，仍然显示坐标
                        const address = `${eventLng},${eventLat}`;
                        document.getElementById('eventLocation').textContent = address;
                        
                        // 安全地设置和打开信息窗体
                        try {
                            if (infoWindow) {
                                infoWindow.setContent(`
                                    <div style="padding: 8px;">
                                        <h6>事件位置</h6>
                                        <p>${address}</p>
                                    </div>
                                `);
                                
                                // 确保地图和标记都存在且有效
                                if (map && eventMarker && eventMarker.getPosition) {
                                    const position = eventMarker.getPosition();
                                    if (position) {
                                        infoWindow.open(map, position);
                                    }
                                }
                            }
                        } catch (infoError) {
                            console.error('信息窗体操作失败:', infoError);
                        }
                    }
                }, 1000); // 延迟1秒确保AMap完全加载
                
                eventMarker.on('click', function() {
                    try {
                        // 确保地图和标记都存在且有效
                        if (map && eventMarker && eventMarker.getPosition) {
                            const position = eventMarker.getPosition();
                            if (position) {
                                if (infoWindow) {
                                    infoWindow.open(map, position);
                                }
                            }
                        }
                    } catch (error) {
                        console.error('点击标记打开信息窗体失败:', error);
                    }
                });
            } catch (error) {
                console.error('地图初始化失败:', error);
                document.getElementById('eventMap').innerHTML = '<div class="text-muted text-center pt-5">地图初始化失败</div>';
            }
        }
        
        // 加载最新响应者位置
        async function loadLatestResponderLocation(eventId, map, eventLat, eventLng) {
            try {
                const response = await fetch(`/ercms/api/events/${eventId}/latest-responder-location`, {
                    headers: AuthManager.getAuthHeaders()
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data) {
                        const responderLocation = result.data;
                        if (responderLocation && responderLocation.includes(',')) {
                            const parts = responderLocation.split(',');
                            if (parts.length === 2) {
                                const responderLng = Number(parts[0].trim());
                                const responderLat = Number(parts[1].trim());
                                
                                if (!isNaN(responderLat) && !isNaN(responderLng) &&
                                    (Math.abs(responderLat - eventLat) > 0.0001 || Math.abs(responderLng - eventLng) > 0.0001)) {
                                    
                                    // 响应者位置标记（蓝色）
                                    const responderMarker = new AMap.Marker({
                                        position: new AMap.LngLat(responderLng, responderLat),
                                        map: map,
                                        title: '响应者位置',
                                        icon: new AMap.Icon({
                                            size: new AMap.Size(28, 28),
                                            image: ''
                                        })
                                    });
                                    
                                    // 响应者位置信息窗体
                                    let responderInfoWindow = null;
                                    try {
                                        responderInfoWindow = new AMap.InfoWindow({
                                            content: `
                                                <div style="padding: 8px;">
                                                    <h6>响应者位置</h6>
                                                    <p>坐标: ${responderLng.toFixed(4)}, ${responderLat.toFixed(4)}</p>
                                                </div>
                                            `
                                        });
                                    } catch (error) {
                                        console.error('创建响应者信息窗体失败:', error);
                                        responderInfoWindow = null;
                                    }
                                    
                                    responderMarker.on('click', function() {
                                        try {
                                            // 确保地图和标记都存在且有效
                                            if (map && responderMarker && responderMarker.getPosition && responderInfoWindow) {
                                                const position = responderMarker.getPosition();
                                                if (position) {
                                                    responderInfoWindow.open(map, position);
                                                }
                                            }
                                        } catch (error) {
                                            console.error('点击响应者标记打开信息窗体失败:', error);
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('获取响应者位置失败:', error);
            }
        }

        // 加载时间线
        async function loadTimeline(eventId) {
            try {
                const response = await fetch(`/ercms/api/events/${eventId}/timeline`, {
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    const timeline = await response.json();
                    displayTimeline(timeline);
                } else {
                    const error = await response.text();
                    console.error('加载时间线失败', error);
                    document.getElementById('timeline').innerHTML = '<div class="loading">加载时间线失败</div>';
                }
            } catch (error) {
                console.error('加载时间线失败', error);
                document.getElementById('timeline').innerHTML = '<div class="loading">加载时间线失败</div>';
            }
        }

        // 显示时间线
        function displayTimeline(timeline) {
            const timelineDiv = document.getElementById('timeline');
            if (timeline.length === 0) {
                timelineDiv.innerHTML = '<div class="loading">暂无时间线数据</div>';
                return;
            }

            timelineDiv.innerHTML = timeline.map(item => `
                <div class="timeline-item">
                    <div class="timeline-time">${formatTime(item.time)}</div>
                    <div class="timeline-content">${item.description}</div>
                </div>
            `).join('');
        }

        // 格式化时间
        function formatTime(timeString) {
            const date = new Date(timeString);
            return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        }

        // 获取当前位置
        function getCurrentLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    position => {
                        const { latitude, longitude } = position.coords;
                        document.getElementById('currentLocation').textContent = `${latitude.toFixed(4)}, ${longitude.toFixed(4)}`;
                        document.getElementById('lastLocationUpdate').textContent = new Date().toLocaleTimeString('zh-CN');
                        
                        // 如果有当前任务，更新位置到服务器
                        if (currentEvent) {
                            updateLocation(latitude, longitude);
                        }
                        
                        showSuccess('位置获取成功');
                    },
                    error => {
                        console.error('获取位置失败:', error);
                        document.getElementById('currentLocation').textContent = '获取失败';
                        showError('获取地理位置失败，请检查浏览器权限');
                    },
                    { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
                );
            } else {
                document.getElementById('currentLocation').textContent = '不支持';
                showError('您的浏览器不支持地理位置功能');
            }
        }

        // 开始位置追踪
        function startLocationTracking() {
            if (isLocationTracking) {
                showError('位置追踪已在运行中');
                return;
            }
            
            if (!navigator.geolocation) {
                showError('您的浏览器不支持地理位置功能');
                return;
            }
            
            // 立即获取一次位置
            getCurrentLocation();
            
            // 设置定时追踪（每30秒更新一次位置）
            locationTrackingInterval = setInterval(() => {
                getCurrentLocation();
            }, 30000); // 30秒
            
            isLocationTracking = true;
            showSuccess('位置追踪已开始，每30秒更新一次位置');
            
            // 更新按钮状态
            updateLocationTrackingButtons();
        }

        // 停止位置追踪
        function stopLocationTracking() {
            if (!isLocationTracking) {
                showError('位置追踪未在运行');
                return;
            }
            
            if (locationTrackingInterval) {
                clearInterval(locationTrackingInterval);
                locationTrackingInterval = null;
            }
            
            isLocationTracking = false;
            showSuccess('位置追踪已停止');
            
            // 更新按钮状态
            updateLocationTrackingButtons();
        }

        // 更新位置追踪按钮状态
        function updateLocationTrackingButtons() {
            const startBtn = document.querySelector('button[onclick="startLocationTracking()"]');
            const stopBtn = document.querySelector('button[onclick="stopLocationTracking()"]');
            
            if (isLocationTracking) {
                if (startBtn) startBtn.disabled = true;
                if (stopBtn) stopBtn.disabled = false;
            } else {
                if (startBtn) startBtn.disabled = false;
                if (stopBtn) stopBtn.disabled = true;
            }
        }

        // 加载上次保存的位置信息
        function loadLastKnownLocation() {
            const lat = localStorage.getItem('lastKnownLatitude');
            const lng = localStorage.getItem('lastKnownLongitude');
            const updateTime = localStorage.getItem('lastLocationUpdateTime');
            
            if (lat && lng) {
                document.getElementById('currentLocation').textContent = `${parseFloat(lng).toFixed(4)}, ${parseFloat(lat).toFixed(4)}`;
                if (updateTime) {
                    const updateDate = new Date(updateTime);
                    document.getElementById('lastLocationUpdate').textContent = updateDate.toLocaleString('zh-CN');
                }
                return true;
            }
            return false;
        }

        // 接受任务
        function acceptEvent(eventId) {
            if (confirm('确认接受任务？')) {
                updateEventStatus(eventId, 'ACCEPTED');
            }
        }

        // 开始前往
        function startEnRoute(eventId) {
            if (confirm('确认开始前往现场？')) {
                updateEventStatus(eventId, 'EN_ROUTE');
            }
        }

        // 到达现场
        function arriveAtScene(eventId) {
            if (confirm('确认已到达现场？')) {
                updateEventStatus(eventId, 'ARRIVED');
            }
        }

        // 开始处理
        function startProcessing(eventId) {
            if (confirm('确认开始处理？')) {
                updateEventStatus(eventId, 'IN_PROGRESS');
            }
        }

        // 完成任务
        async function completeTask(eventId) {
            if (confirm('确认完成任务？完成后将跳转到报告页面')) {
                // 直接跳转到任务报告页面
                window.location.href = `/ercms/task-report?eventId=${eventId}`;
            }
        }

        // 任务完成后刷新数据
        function refreshAfterCompletion() {
            loadCurrentEvent();
            loadTodayCompletedCount();
            // 如果历史任务面板有内容，也刷新一下
            const historyDiv = document.getElementById('historyEvents');
            if (historyDiv.innerHTML.includes('今日完成任务') || 
                historyDiv.innerHTML.includes('历史记录')) {
                loadTodayCompletedEvents();
            }
        }

        async function updateLocation(latitude, longitude) {
            // 保存位置到本地存储
            localStorage.setItem('lastKnownLatitude', latitude.toString());
            localStorage.setItem('lastKnownLongitude', longitude.toString());
            localStorage.setItem('lastLocationUpdateTime', new Date().toISOString());
            
            // 如果有当前任务，更新位置到服务器
            if (currentEvent) {
                try {
                    const response = await fetch(`/ercms/api/events/${currentEvent.id}/update-location`, {
                        method: 'POST',
                        headers: AuthManager.getAuthHeaders(),
                        body: JSON.stringify({ latitude, longitude })
                    });
                    if (!response.ok) {
                        const error = await response.text();
                        console.error('更新位置失败:', error);
                        showError('更新位置失败: ' + error);
                    } else {
                        console.log('位置已更新到服务器');
                    }
                } catch (error) {
                    console.error('更新位置失败:', error);
                    showError('更新位置失败: ' + error.message);
                }
            } else {
                console.log('无当前任务，位置仅保存到本地');
            }
        }

        async function updateSafetyStatus(status) {
            if (!currentEvent) return;
            try {
                const response = await fetch(`/ercms/api/events/${currentEvent.id}/safety-status`, {
                    method: 'POST',
                    headers: AuthManager.getAuthHeaders(),
                    body: JSON.stringify({ safetyStatus: status })
                });
                if (response.ok) {
                    currentEvent = await response.json();
                    updateSafetyStatusDisplay(currentEvent.safetyStatus);
                    loadTimeline(currentEvent.id);
                    showSuccess('安全状态更新成功');
                    // 更新人员状态
                    updatePersonnelStatus();
                } else {
                    const error = await response.text();
                    showError('更新安全状态失败: ' + error);
                }
            } catch (error) {
                console.error('更新安全状态失败', error);
                showError('更新安全状态失败: ' + error.message);
            }
        }

        async function requestSupport(type, description) {
            if (!currentEvent) return;
            try {
                const response = await fetch(`/ercms/api/events/${currentEvent.id}/request-support`, {
                    method: 'POST',
                    headers: AuthManager.getAuthHeaders(),
                    body: JSON.stringify({ supportType: type, description })
                });
                if (response.ok) {
                    currentEvent = await response.json();
                    updateSupportRequestDisplay(currentEvent.supportRequested, currentEvent.supportType);
                    loadTimeline(currentEvent.id);
                    showSuccess('支援请求已发送');
                    // 更新人员状态
                    updatePersonnelStatus();
                } else {
                    const error = await response.text();
                    showError('请求支援失败: ' + error);
                }
            } catch (error) {
                console.error('请求支援失败:', error);
                showError('请求支援失败: ' + error.message);
            }
        }

        async function cancelSupport() {
            if (!currentEvent) return;
            try {
                const response = await fetch(`/ercms/api/events/${currentEvent.id}/cancel-support`, { 
                    method: 'POST',
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    currentEvent = await response.json();
                    updateSupportRequestDisplay(currentEvent.supportRequested, currentEvent.supportType);
                    loadTimeline(currentEvent.id);
                    showSuccess('支援请求已取消');
                    // 更新人员状态
                    updatePersonnelStatus();
                } else {
                    const error = await response.text();
                    showError('取消支援失败: ' + error);
                }
            } catch (error) {
                console.error('取消支援失败:', error);
                showError('取消支援失败: ' + error.message);
            }
        }

        async function sendSOS() {
            if (!currentEvent) return;
            const message = prompt('请输入SOS消息：');
            if (message === null) return;
            
            try {
                const response = await fetch(`/ercms/api/events/${currentEvent.id}/sos`, {
                    method: 'POST',
                    headers: AuthManager.getAuthHeaders(),
                    body: JSON.stringify({ message })
                });
                if (response.ok) {
                    currentEvent = await response.json();
                    updateSafetyStatusDisplay(currentEvent.safetyStatus);
                    loadTimeline(currentEvent.id);
                    
                    // 显示紧急警报
                    document.getElementById('emergencyMessage').textContent = `SOS: ${message}`;
                    document.getElementById('emergencyAlert').style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('emergencyAlert').style.display = 'none';
                    }, 10000);
                    
                    showSuccess('SOS紧急求助已发送');
                    // 更新人员状态
                    updatePersonnelStatus();
                } else {
                    const error = await response.text();
                    showError('发送SOS失败: ' + error);
                }
            } catch (error) {
                console.error('发送SOS失败:', error);
                showError('发送SOS失败: ' + error.message);
            }
        }

        function getPosition() {
            return new Promise((resolve, reject) => {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(resolve, reject, {
                        enableHighAccuracy: true,
                        timeout: 10000,
                        maximumAge: 0
                    });
                } else {
                    reject(new Error('浏览器不支持地理位置'));
                }
            });
        }

        // 统一的事件状态更新函数
        async function updateEventStatus(eventId, status) {
            try {
                let url = '';
                let method = 'POST';
                let body = null;
                
                switch (status) {
                    case 'ACCEPTED':
                        url = `/ercms/api/events/${eventId}/accept`;
                        break;
                    case 'EN_ROUTE':
                        url = `/ercms/api/events/${eventId}/en-route`;
                        // 开始前往时获取位置信息
                        try {
                            const position = await getPosition();
                            body = JSON.stringify({
                                latitude: position.coords.latitude,
                                longitude: position.coords.longitude
                            });
                        } catch (error) {
                            console.warn('无法获取位置信息:', error);
                            body = JSON.stringify({});
                        }
                        break;
                    case 'ARRIVED':
                        url = `/ercms/api/events/${eventId}/arrive`;
                        // 到达现场时获取位置信息
                        try {
                            const position = await getPosition();
                            body = JSON.stringify({
                                latitude: position.coords.latitude,
                                longitude: position.coords.longitude
                            });
                        } catch (error) {
                            console.warn('无法获取位置信息:', error);
                            body = JSON.stringify({});
                        }
                        break;
                    case 'IN_PROGRESS':
                        url = `/ercms/api/events/${eventId}/start-processing`;
                        break;
                    case 'RETURNING':
                        url = `/ercms/api/events/${eventId}/return`;
                        break;
                    default:
                        throw new Error('未知的状态: ' + status);
                }
                
                const headers = AuthManager.getAuthHeaders();
                const response = await fetch(url, { method, headers, body });
                
                if (response.ok) {
                    const updatedEvent = await response.json();
                    currentEvent = updatedEvent;
                    displayCurrentEvent(updatedEvent);
                    loadTimeline(eventId);
                    showSuccess(`状态更新成功: ${getStatusDisplay(status)}`);
                    // 更新人员状态
                    updatePersonnelStatus();
                    // 更新安全状态和支援请求显示
                    if (updatedEvent.safetyStatus) {
                        updateSafetyStatusDisplay(updatedEvent.safetyStatus);
                    }
                    if (updatedEvent.supportRequested !== undefined) {
                        updateSupportRequestDisplay(updatedEvent.supportRequested, updatedEvent.supportType);
                    }
                } else {
                    const error = await response.text();
                    showError(`状态更新失败: ${error}`);
                    // 重置安全状态和支援请求显示
                    updateSafetyStatusDisplay('SAFE');
                    updateSupportRequestDisplay(false, null);
                }
            } catch (error) {
                console.error('状态更新失败', error);
                showError('状态更新失败: ' + error.message);
                // 重置安全状态和支援请求显示
                updateSafetyStatusDisplay('SAFE');
                updateSupportRequestDisplay(false, null);
            }
        }

        // 显示状态文本
        function getStatusDisplay(status) {
            const statusMap = {
                'PENDING': '待处理',
                'ASSIGNED': '已指派',
                'ACCEPTED': '已接受',
                'EN_ROUTE': '前往中',
                'ARRIVED': '已到达',
                'IN_PROGRESS': '处理中',
                'COMPLETED': '已完成',
                'RETURNING': '返回中',
                'RESOLVED': '已解决',
                'CLOSED': '已关闭'
            };
            return statusMap[status] || status;
        }

        // 加载今日完成任务
        async function loadTodayCompletedEvents() {
            try {
                const response = await fetch('/ercms/api/events/my-today-completed-events', {
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    const events = await response.json();
                    displayHistoryEvents(events, '今日完成任务');
                } else {
                    showError('加载今日完成任务失败');
                }
            } catch (error) {
                console.error('加载今日完成任务失败:', error);
                showError('加载今日完成任务失败: ' + error.message);
                // 重置安全状态和支援请求显示
                updateSafetyStatusDisplay('SAFE');
                updateSupportRequestDisplay(false, null);
            }
        }

        // 加载历史记录
        async function loadEventHistory() {
            try {
                const response = await fetch('/ercms/api/events/my-history', {
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    const events = await response.json();
                    displayHistoryEvents(events, '历史记录');
                } else {
                    showError('加载历史记录失败');
                }
            } catch (error) {
                console.error('加载历史记录失败:', error);
                showError('加载历史记录失败: ' + error.message);
                // 重置安全状态和支援请求显示
                updateSafetyStatusDisplay('SAFE');
                updateSupportRequestDisplay(false, null);
            }
        }

        // 显示历史任务
        function displayHistoryEvents(events, title) {
            const historyDiv = document.getElementById('historyEvents');
            if (events.length === 0) {
                historyDiv.innerHTML = `<div class="loading">暂无${title}</div>`;
                return;
            }

            historyDiv.innerHTML = events.map(event => `
                <div class="timeline-item">
                    <div class="timeline-time">${formatTime(event.completedTime || event.updatedAt || event.createdAt)}</div>
                    <div class="timeline-content">
                        <div style="font-weight: bold; margin-bottom: 5px;">${event.title || '无标题'}</div>
                        <div style="font-size: 12px; color: #666; margin-bottom: 5px;">
                            状态: ${getStatusDisplay(event.status)} | 
                            类型: ${event.eventType ? event.eventType.name : '未知'} | 
                            位置: ${event.location || '未知'}
                        </div>
                        <div style="font-size: 12px; color: #666;">
                            ${event.description || '无描述'}
                        </div>
                        ${event.responderNotes ? `<div style="font-size: 12px; color: #28a745; margin-top: 5px;">完成备注: ${event.responderNotes}</div>` : ''}
                    </div>
                </div>
            `).join('');
        }

        // 加载今日完成任务数量
        async function loadTodayCompletedCount() {
            try {
                const response = await fetch('/ercms/api/events/my-today-completed-events', {
                    headers: AuthManager.getAuthHeaders()
                });
                if (response.ok) {
                    const events = await response.json();
                    document.getElementById('todayTasks').textContent = events.length;
                    
                    // 计算完成率：今日完成任务数量 / (今日完成任务数量 + 当前任务数量)
                    const completedCount = events.length;
                    const currentTaskCount = currentEvent ? 1 : 0;
                    const totalTasks = completedCount + currentTaskCount;
                    
                    if (totalTasks > 0) {
                        const completionRate = Math.round((completedCount / totalTasks) * 100);
                        document.getElementById('completionRate').textContent = completionRate + '%';
                    } else {
                        document.getElementById('completionRate').textContent = '0%';
                    }
                }
            } catch (error) {
                console.error('加载今日完成任务数量失败:', error);
            }
        }

        // 完成任务
        async function completeEvent() {
            if (!currentEvent) {
                showError('没有当前任务');
                return;
            }

            if (!confirm('确定要完成这个任务吗？')) {
                return;
            }

            try {
                const response = await fetch('/ercms/api/completion/complete', {
                    method: 'POST',
                    headers: AuthManager.getAuthHeaders(),
                    body: JSON.stringify({
                        eventId: currentEvent.id,
                        completionNotes: document.getElementById('completionNotes').value
                    })
                });

                if (response.ok) {
                    showSuccess('任务完成了');
                    // 清空完成备注
                    document.getElementById('completionNotes').value = '';
                    // 重新加载当前任务（应该会显示没有当前任务）
                    loadCurrentEvent();
                    // 更新完成率
                    loadTodayCompletedCount();
                    // 重置安全状态和支援请求显示
                    updateSafetyStatusDisplay('SAFE');
                    updateSupportRequestDisplay(false, null);
                } else {
                    const error = await response.text();
                    showError('完成任务失败: ' + error);
                }
            } catch (error) {
                console.error('完成任务失败:', error);
                showError('完成任务失败: ' + error.message);
                // 重置安全状态和支援请求显示
                updateSafetyStatusDisplay('SAFE');
                updateSupportRequestDisplay(false, null);
            }
        }

        // 安全状态显示函数
        function updateSafetyStatusDisplay(safetyStatus) {
            const statusDiv = document.getElementById('safetyStatus');
            if (!statusDiv) return;
            let text = '安全状态：';
            let cssClass = 'safety-status ';
            switch (safetyStatus) {
                case 'SAFE':
                    text += '安全';
                    cssClass += 'safety-safe';
                    break;
                case 'CAUTION':
                    text += '注意';
                    cssClass += 'safety-caution';
                    break;
                case 'DANGER':
                    text += '危险';
                    cssClass += 'safety-danger';
                    break;
                case 'SOS':
                    text += '紧急求助';
                    cssClass += 'safety-danger';
                    break;
                default:
                    text += safetyStatus || '未知';
                    cssClass += 'safety-unknown';
            }
            statusDiv.textContent = text;
            statusDiv.className = cssClass;
        }

        // 支援请求显示函数
        function updateSupportRequestDisplay(supportRequested, supportType) {
            const supportDiv = document.getElementById('supportRequest');
            const supportInfo = document.getElementById('supportInfo');
            if (!supportDiv || !supportInfo) return;
            
            if (supportRequested && supportType) {
                let typeText = '';
                switch (supportType) {
                    case 'MEDICAL':
                        typeText = '医疗支援';
                        break;
                    case 'POLICE':
                        typeText = '警力支援';
                        break;
                    case 'FIRE':
                        typeText = '消防支援';
                        break;
                    default:
                        typeText = supportType;
                }
                supportInfo.textContent = `已请求${typeText}`;
                supportDiv.style.display = 'block';
            } else {
                supportDiv.style.display = 'none';
            }
        }

        // 更新人员状态
        function updatePersonnelStatus() {
            if (!isLoggedIn) {
                document.getElementById('currentStatus').textContent = '离线';
                return;
            }
            
            // 根据当前任务状态确定人员状态
            let personnelStatus = '在线';
            let statusColor = 'text-success';
            
            if (currentEvent) {
                switch (currentEvent.responderStatus) {
                    case 'ACCEPTED':
                    case 'EN_ROUTE':
                    case 'ARRIVED':
                    case 'IN_PROGRESS':
                        personnelStatus = '忙碌';
                        statusColor = 'text-warning';
                        break;
                    case 'COMPLETED':
                    case 'RETURNING':
                        personnelStatus = '返回中';
                        statusColor = 'text-info';
                        break;
                    case 'RESOLVED':
                    case 'CLOSED':
                        personnelStatus = '空闲';
                        statusColor = 'text-success';
                        break;
                    default:
                        personnelStatus = '待命';
                        statusColor = 'text-primary';
                }
            } else {
                personnelStatus = '待命';
                statusColor = 'text-primary';
            }
            
            const statusElement = document.getElementById('currentStatus');
            statusElement.textContent = personnelStatus;
            statusElement.className = `status-value ${statusColor}`;
        }

        // 检查AMap是否已加载
        function checkAMapLoaded() {
            return new Promise((resolve) => {
                if (typeof AMap !== 'undefined' && AMap.Map) {
                    amapLoaded = true;
                    resolve(true);
                } else if (window.amapLoadStatus && window.amapLoadStatus.loaded) {
                    // 如果标记为已加载但AMap对象不存在，等待一下
                    setTimeout(() => {
                        if (typeof AMap !== 'undefined' && AMap.Map) {
                            amapLoaded = true;
                            resolve(true);
                        } else {
                            console.error('AMap标记为已加载但对象不存在');
                            resolve(false);
                        }
                    }, 500);
                } else {
                    // 尝试重新加载AMap
                    if (window.loadAMapScript) {
                        window.loadAMapScript().then(() => {
                            amapLoaded = true;
                            resolve(true);
                        }).catch(() => {
                            console.error('AMap重新加载失败');
                            resolve(false);
                        });
                    } else {
                        // 等待AMap加载
                        const checkInterval = setInterval(() => {
                            if (typeof AMap !== 'undefined' && AMap.Map) {
                                amapLoaded = true;
                                clearInterval(checkInterval);
                                resolve(true);
                            }
                        }, 100);
                        
                        // 设置超时，避免无限等待
                        setTimeout(() => {
                            clearInterval(checkInterval);
                            console.error('AMap加载超时');
                            resolve(false);
                        }, 10000); // 10秒超时
                    }
                }
            });
        }
    </script>
</body>
</html>
